<template>
  <div id="page_company_list">
    <Row style="margin: 5px 0px 10px 0px">
      <Input
        v-model="searchKeyword"
        :placeholder="$t('sysP.trainCp')"
        style="width: 200px; margin-right: 20px"
      />
      <Button
        class="btnWhite"
        type="primary"
        icon="ios-search"
        style="margin-right: 20px"
        @click="search"
        >{{ $t("search") }}</Button
      >
      <Button
        class="btnWhite"
        type="primary"
        icon="md-add"
        @click="showAddModal"
        >{{ $t("sysP.addTrainC") }}</Button
      >
    </Row>
    <Row class="search_row"> </Row>
    <Row class="list_row">
      <Table
        :columns="columns"
        border
        :data="dataList"
        stripe
        :no-data-text="noDataMsg"
      >
        <template slot-scope="{ row, index }" slot="seq">
          {{ (currentPage - 1) * pageSize + index + 1 }}
        </template>
        <template slot-scope="{ row, index }" slot="admin">
          <div>
            <div style="text-align: center">{{ row.adminName }}</div>
            <div style="text-align: center">{{ row.adminPhone }}</div>
          </div>
        </template>
      </Table>
      <div class="div_page">
        <Page
          :total="totalCount"
          :current="currentPage"
          :page-size="pageSize"
          show-total
          show-elevator
          prev-text="<"
          next-text=">"
          @on-change="pageChg"
        />
      </div>
    </Row>

    <!-- 新增弹窗 -->
    <Modal
      v-model="entityModelVisiable"
      :mask-closable="false"
      width="600"
      :title="entityModelTitle"
    >
      <Form
        ref="entityFormRef"
        :model="entityForm"
        :rules="addFormRules"
        :label-width="120"
      >
        <FormItem :label="$t('sysP.trainCname')" prop="name">
          <Input
            v-model="entityForm.name"
            :placeholder="$t('sysP.trainCp')"
          ></Input>
        </FormItem>
        <FormItem :label="$t('sysP.trainAddress')" prop="addr">
          <Input
            v-model="entityForm.addr"
            :placeholder="$t('sysP.trainAddressIn')"
          ></Input>
        </FormItem>
        <FormItem
          :label="$t('common.phone')"
          prop="adminPhone"
          v-show="entityForm.id == '' && $i18n.locale === 'zh-CN'"
        >
          <Input
            v-model="entityForm.adminPhone"
            :placeholder="$t('sysP.adPhone1')"
          ></Input>
        </FormItem>
        <FormItem
          :label="$t('common.mail')"
          prop="adminMail"
          v-show="entityForm.id == '' && $i18n.locale === 'en-US'"
        >
          <Input
            v-model="entityForm.adminMail"
            :placeholder="$t('sysP.adAdmail')"
          ></Input>
        </FormItem>
        <FormItem
          :label="$t('common.name')"
          prop="adminName"
          v-show="entityForm.id == ''"
        >
          <Input
            v-model="entityForm.adminName"
            :placeholder="$t('sysP.setAdname1')"
          ></Input>
        </FormItem>
        <FormItem
          :label="$t('common.password')"
          prop="password"
          v-show="entityForm.id == ''"
        >
          <Input
            v-model="entityForm.password"
            type="password"
            :placeholder="$t('sysP.setAdpwd1')"
          ></Input>
        </FormItem>
        <FormItem
          :label="$t('loginL.confirmPwd')"
          prop="confirmPassword"
          v-show="entityForm.id == ''"
        >
          <Input
            v-model="entityForm.confirmPassword"
            type="password"
            :placeholder="$t('sysP.againPwd')"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: center">
        <Button @click="entityModelVisiable = false">{{ $t("cancel") }}</Button>
        <Button
          type="primary"
          @click="saveOrUpdate"
          :loading="saveLoading"
          style="margin-left: 15px"
        >
          <span v-if="!saveLoading">{{ $t("save") }}</span>
          <span v-else>{{ $t("save") }}....</span>
        </Button>
      </div>
    </Modal>

    <!-- 更换管理员弹窗 -->
    <Modal
      v-model="changeAdminModelVisiable"
      :mask-closable="false"
      width="600"
      :title="$t('sysP.changeAd')"
    >
      <Row>
        <Form
          ref="changeFormRef"
          :model="changeForm"
          :rules="changeFormRules"
          :label-width="160"
        >
          <FormItem :label="$t('sysP.nowAd')" prop="name">
            
            {{ changeForm.oldAdminName }}( {{ $i18n.locale === 'zh-CN' ? changeForm.oldAdminPhone : changeForm.oldAdminMail }})
          </FormItem>
          <FormItem
            :label="$t('common.phone')"
            prop="phone"
            v-show="$i18n.locale === 'zh-CN'"
          >
            <Input
              v-model="changeForm.phone"
              :placeholder="$t('sysP.adPhone')"
              style="width: 60%"
            ></Input>
            <Button
              type="info"
              icon="ios-search"
              style="margin-left: 20px"
              @click="validAdminPhone"
              >{{ $t("sysP.detection") }}</Button
            >
          </FormItem>
          <FormItem
            :label="$t('common.mail')"
            prop="mail"
            v-show="$i18n.locale === 'en-US'"
          >
            <Input
              v-model="changeForm.mail"
              :placeholder="$t('sysP.adMailNew')"
              style="width: 60%"
            ></Input>
            <Button
              type="info"
              icon="ios-search"
              style="margin-left: 20px"
              @click="validAdminPhone"
              >{{ $t("sysP.detection") }}</Button
            >
          </FormItem>

          <div
            style="padding: 0px 0px 16px 0px; margin-left: 160px; color: red"
            v-show="changeForm.validMsg.length > 0"
          >
            {{ changeForm.validMsg }}
          </div>
          <FormItem
            :label="$t('common.name')"
            prop="nickName"
            v-if="changeForm.valid && changeForm.newAdminId.length == 0"
          >
            <Input
              v-model="changeForm.nickName"
              :placeholder="$t('sysP.setAdname')"
            ></Input>
          </FormItem>
          <FormItem
            :label="$t('common.password')"
            prop="password"
            v-if="changeForm.valid && changeForm.newAdminId.length == 0"
          >
            <Input
              v-model="changeForm.password"
              type="password"
              :placeholder="$t('sysP.setAdpwd')"
            ></Input>
          </FormItem>
          <FormItem
            :label="$t('loginL.confirmPwd')"
            prop="confirmPassword"
            v-if="changeForm.valid && changeForm.newAdminId.length == 0"
          >
            <Input
              v-model="changeForm.confirmPassword"
              type="password"
              :placeholder="$t('sysP.againPwd')"
            ></Input>
          </FormItem>
        </Form>
      </Row>
      <div slot="footer" style="text-align: center">
        <Button @click="changeAdminModelVisiable = false">{{
          $t("cancel")
        }}</Button>
        <Button
          type="primary"
          @click="updateAdmin"
          :loading="saveLoading"
          style="margin-left: 15px"
        >
          <span v-if="!saveLoading">{{ $t("sysP.change") }}</span>
          <span v-else>{{ $t("sysP.change") }}....</span>
        </Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import TrainCenterApi from "@/api/trainCenterApi";
import { isEmpty, copyObj } from "@/libs/util";

export default {
  name: "train-center-mgr",
  data() {
    const validatePassCheck = (rule, value, callback) => {
      if (value !== this.entityForm.password) {
        callback(new Error(this.$t("common.pwd2Diff")));
      } else {
        callback();
      }
    };
    const changeFormPassCheck = (rule, value, callback) => {
      if (value !== this.changeForm.password) {
        callback(new Error(this.$t("common.pwd2Diff")));
      } else {
        callback();
      }
    };
    return {
      changeAdminModelVisiable: false,
      changeForm: {
        oldAdminId: "",
        oldAdminName: "",
        oldAdminPhone: "",
        oldAdminMail:'',
        newAdminId: "",
        phone: "",
        mail: "",
        nickName: "",
        trainCenterId: "",
        hasCheck: false,
        valid: false,
        validMsg: "",
        password: "******",
        confirmPassword: "******",
      },
      changeFormRules: {
        nickName: [
          {
            required: true,
            message: this.$t("common.nameMustTips"),
            trigger: "blur",
          },
          {
            type: "string",
            min: 2,
            max: 32,
            message: this.$t("common.name2and32"),
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: this.$i18n.locale === "zh-CN" ? true : false,
            message: this.$t("common.phoneMustTips"),
            trigger: "blur",
          },
          {
            type: "string",
            pattern: "^[1][3-9][0-9]{9}$",
            message: this.$t("common.phoneFormate"),
            trigger: "blur",
          },
        ],
        mail: [
          {
            required: this.$i18n.locale === "zh-CN" ? false : true,
            message: this.$t("common.emailMust"),
            trigger: "blur",
          },
          {
            type: "string",
            pattern: "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
            message: this.$t("common.emailFormate"),
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: this.$t("common.passwordMustTips"),
            trigger: "blur",
          },
          {
            type: "string",
            min: 6,
            max: 18,
            message: this.$t("common.password6and8"),
            trigger: "blur",
          },
        ],
        confirmPassword: [
          {
            required: true,
            message: this.$t("loginL.pwdConfirmPlaceTips"),
            trigger: "blur",
          },
          { validator: changeFormPassCheck, trigger: "blur" },
        ],
      },
      noDataMsg: this.$t("common.noData"),
      searchKeyword: "",
      scrollTop: 0,
      saveLoading: false,
      entityForm: {
        id: "",
        name: "",
        addr: "",
        adminPhone: "",
        adminMail: "",
        adminName: "",
        password: "",
        confirmPassword: "",
      },
      entityModelTitle: this.$t("sysP.addEsBtn"),
      addFormRules: {
        name: [
          {
            required: true,
            message: this.$t("common.nameMustTips"),
            trigger: "blur",
          },
          {
            type: "string",
            min: 2,
            max: 32,
            message: this.$t("common.name2and32"),
            trigger: "blur",
          },
        ],
        addr: [
          {
            required: true,
            message: this.$t("common.addressMust"),
            trigger: "blur",
          },
          {
            type: "string",
            max: 64,
            message: this.$t("common.namelenLow64Tips"),
            trigger: "blur",
          },
        ],
        adminPhone: [
          {
            required: this.$i18n.locale === "zh-CN" ? true : false,
            message: this.$t("common.phoneMustTips"),
            trigger: "blur",
          },
          {
            type: "string",
            pattern: "^[1][3-9][0-9]{9}$",
            message: this.$t("common.phoneFormate"),
            trigger: "blur",
          },
        ],
        adminMail: [
          {
            required: this.$i18n.locale === "zh-CN" ? false : true,
            message: this.$t("common.emailMust"),
            trigger: "blur",
          },
          {
            type: "string",
            pattern: "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
            message: this.$t("common.emailFormate"),
            trigger: "blur",
          },
        ],
        adminName: [
          {
            required: true,
            message: this.$t("common.nameMustTips"),
            trigger: "blur",
          },
          {
            type: "string",
            min: 2,
            max: 32,
            message: this.$t("common.name2and32"),
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: this.$t("common.passwordMustTips"),
            trigger: "blur",
          },
          {
            type: "string",
            min: 6,
            max: 18,
            message: this.$t("common.password6and8"),
            trigger: "blur",
          },
        ],
        confirmPassword: [
          {
            required: true,
            message: this.$t("loginL.pwdConfirmPlaceTips"),
            trigger: "blur",
          },
          { validator: validatePassCheck, trigger: "blur" },
        ],
      },
      entityModelVisiable: false,
      totalCount: 122,
      currentPage: 1,
      pageSize: 10,
      dataList: [],
      columns: [
        {
          title: this.$t("common.seq"),
          slot: "seq",
          width: "110",
          render: (h, params) => {
            return h(
              "span",
              {
                class: "sortBlock",
              },
              params.index + 1
            );
          },
        },
        {
          title: this.$t("sysP.trainCname"),
          key: "name",
        },
        {
          title: this.$t("sysP.address"),
          key: "addr",
        },
        {
          title: this.$t("sysP.administrators"),
          slot: "admin",
        },
        {
          title: this.$i18n.locale === 'zh-CN' ? this.$t('common.adminPhone') : this.$t('common.adminMail'), 
          key: this.$i18n.locale === 'zh-CN' ? "adminPhone" : "adminMail",
        },
        {
          title: this.$t("homeP.students"),
          key: "trainerCount",
        },
        {
          title: this.$t("homeP.coaches"),
          key: "coachCount",
        },
        {
          title: this.$t("homeP.devices"),
          key: "deviceCount",
        },
        {
          title: this.$t("common.optColumn"),
          key: "action",
          width: 410,
          render: (h, params) => {
            return h("div", [
              // h('Button', {
              //   props: {
              //     type: 'info',
              //     size: 'small'
              //   },
              //   style: {
              //     marginRight: '15px'
              //   },
              //   on: {
              //     click: () => {
              //       this.detail(params.row.id);
              //     }
              //   }
              // }, '查看'),
              h(
                "Button",
                {
                  props: {
                    type: "warning",
                    size: "small",
                  },
                  style: {
                    marginRight: "15px",
                  },
                  class: "btnBlue",
                  on: {
                    click: () => {
                      this.showEditModal(params.row);
                    },
                  },
                },
                this.$t("common.editBtn")
              ),
              h(
                "Button",
                {
                  props: {
                    type: "warning",
                    size: "small",
                  },
                  style: {
                    marginRight: "15px",
                  },
                  class: "btnYellow",
                  on: {
                    click: () => {
                      this.showChangeAdminModal(params.row);
                    },
                  },
                },
                this.$t("sysP.setupA")
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                  },
                  class: "btnRed",
                  on: {
                    click: () => {
                      this.del(params.row);
                    },
                  },
                },
                this.$t("common.deleteBtn")
              ),
            ]);
          },
        },
      ],
    };
  },
  methods: {
    pageChg(selPage) {
      this.currentPage = selPage;
      this.fetchDataList();
    },
    fetchDataList() {
      this.noDataMsg = this.$t("common.loading");
      this.dataList = [];
      var param = { pageSize: this.pageSize, currentPage: this.currentPage };
      if (this.searchKeyword.length > 0) {
        param.name = this.searchKeyword;
      }
      TrainCenterApi.pageResult(param).then(
        (res) => {
          this.dataList = res.data.data.pageResult.items;
          this.totalCount = res.data.data.pageResult.totalCount;
          this.noDataMsg = this.$t("common.noData");
        },
        (error) => {
          this.$Message.error(error.response.data.msg);
        }
      );
    },
    showAddModal() {
      this.$refs.entityFormRef.resetFields();
      this.entityForm = {
        id: "",
        name: "",
        addr: "",
        adminPhone: "",
        adminMail: "",
        adminName: "",
        password: "",
        confirmPassword: "",
      };
      this.entityModelTitle = this.$t("sysP.addTrainC");
      this.entityModelVisiable = true;
    },
    showEditModal(row) {
      // resetFields 会把row也给置为空，因此row要copy一份
      this.$refs.entityFormRef.resetFields();
      this.entityModelVisiable = true;
      this.entityModelTitle = this.$t("sysP.editTrainC");
      this.entityForm = copyObj(row);
      // 设置不展示数据的默认值，否则表单validate不通过
      this.entityForm.password = "******";
      this.entityForm.confirmPassword = "******";
      this.entityForm.adminName = this.$t("sysP.mrUsername");
      this.entityForm.adminPhone = "13800000000";
      this.entityForm.adminMail = "shuhua@163.com";
    },
    saveOrUpdate() {
      this.$refs.entityFormRef.validate((valid) => {
        if (valid) {
          this.saveLoading = true;
          if( this.$i18n.locale === 'zh-CN' ){

          TrainCenterApi.saveOrUpdate(this.entityForm).then(
            (response) => {
              this.saveLoading = false;
              if (this.entityForm.id == "") {
                this.$Message.success(this.$t("sysP.sucTraincenter"));
              } else {
                this.$Message.success(this.$t("common.editSuc"));
              }
              this.$refs.entityFormRef.resetFields();
              this.entityModelVisiable = false;
              this.fetchDataList();
            },
            (error) => {
              this.saveLoading = false;
              this.$Message.error(error.response.data.msg);
            }
          );
          }else{
 TrainCenterApi.saveOrUpdateMail(this.entityForm).then(
            (response) => {
              this.saveLoading = false;
              if (this.entityForm.id == "") {
                this.$Message.success(this.$t("sysP.sucTraincenter"));
              } else {
                this.$Message.success(this.$t("common.editSuc"));
              }
              this.$refs.entityFormRef.resetFields();
              this.entityModelVisiable = false;
              this.fetchDataList();
            },
            (error) => {
              this.saveLoading = false;
              this.$Message.error(error.response.data.msg);
            }
          );
          }
        }
      });
    },
    del(row) {
      this.$Modal.confirm({
        title: this.$t("common.dDeleteTitleConfirm"),
        content: this.$t("sysP.deleteTrainct"),
        okText: this.$t("common.deleteBtn"),
        cancelText: this.$t("cancel"),
        onOk: () => {
          this.doDel(row.id);
        },
      });
    },
    doDel(id) {
      TrainCenterApi.delete(id).then(
        (res) => {
          this.$Message.success(this.$t("common.deleteSuc"));
          this.fetchDataList();
        },
        (error) => {
          this.$Message.error(error.response.data.msg);
        }
      );
    },
    detail(id) {
      const right_main = document.getElementById("right_main");
      this.scrollTop = right_main.scrollTop;
      this.$router.push({ path: "/company/companyDetail/" + id });
    },

    search() {
      this.currentPage = 1;
      this.fetchDataList();
    },
    showChangeAdminModal(row) {
      this.$refs.changeFormRef.resetFields();
      var adminName = row.adminName;
      var adminPhone = row.adminPhone;
      var adminMail = row.adminMail;
      if (isEmpty(adminName)) {
        adminName = this.$t("sysP.notSet");
        adminPhone = this.$t("sysP.notSet");
        adminMail = this.$t("sysP.notSet");
      }
      this.changeForm = {
        oldAdminId: row.adminId,
        oldAdminName: adminName,
        oldAdminPhone: adminPhone,
        oldAdminMail: adminMail,
        newAdminId: "",
        phone: "",
        mail: "",
        trainCenterId: row.id,
        hasCheck: false,
        valid: false,
        nickName: "",
        validMsg: "",
        password: "******",
        confirmPassword: "******",
      };
      this.changeAdminModelVisiable = true;
    },
    validAdminPhone() {
      if (this.$i18n.locale === "zh-CN") {
        if (this.changeForm.phone.length == 0) {
          this.$Message.error(this.$t("common.phonePlaceTips"));
          return;
        }
        const reg = /^[1][3-9][0-9]{9}$/;
        if (!reg.test(this.changeForm.phone)) {
          this.$Message.error(this.$t("common.phoneFormate"));
          return;
        }
        if (this.changeForm.phone == this.changeForm.oldAdminPhone) {
          this.$Message.error(this.$t("sysP.noPhoneSame"));
          return;
        }
        TrainCenterApi.validAdminPhone(this.changeForm.phone).then(
          (res) => {
            const data = res.data.data;
            this.changeForm.hasCheck = true;
            this.changeForm.valid = true;
            this.changeForm.validMsg = data.msg;
            if (data.exists == 1) {
              this.changeForm.newAdminId = data.id;
            } else {
              this.changeForm.password = "";
              this.changeForm.confirmPassword = "";
            }
          },
          (error) => {
            this.changeForm.hasCheck = true;
            this.$Message.error(error.response.data.msg);
          }
        );
      } else {
        if (this.changeForm.mail.length == 0) {
          this.$Message.error(this.$t("common.emailPlaceTips"));
          return;
        }
        const reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!reg.test(this.changeForm.mail)) {
          this.$Message.error(this.$t("common.emailFormate"));
          return;
        }
        if (this.changeForm.mail == this.changeForm.oldAdminMail) {
          this.$Message.error(this.$t("sysP.noMailSame"));
          return;
        }
        TrainCenterApi.validAdminMail(this.changeForm.mail).then(
          (res) => {
            const data = res.data.data;
            this.changeForm.hasCheck = true;
            this.changeForm.valid = true;
            this.changeForm.validMsg = data.msg;
            if (data.exists == 1) {
              this.changeForm.newAdminId = data.id;
            } else {
              this.changeForm.password = "";
              this.changeForm.confirmPassword = "";
            }
          },
          (error) => {
            this.changeForm.hasCheck = true;
            this.$Message.error(error.response.data.msg);
          }
        );
      }
    },
    updateAdmin() {
      this.$refs.changeFormRef.validate((valid) => {
        if (valid) {
          if (!this.changeForm.hasCheck) {
            this.$Message.error(this.$t("sysP.detectionBtn"));
            return;
          }

          if (this.$i18n.locale === "zh-CN") {
            if (!this.changeForm.valid) {
              this.$Message.error(this.$t("sysP.phoneNoc"));
              return;
            }
          } else {
            if (!this.changeForm.valid) {
              this.$Message.error(this.$t("sysP.mailNoc"));
              return;
            }
          }

          var param = {
            oldAdminId: this.changeForm.oldAdminId,
          };
          if (this.changeForm.newAdminId.length > 0) {
            param.newAdminId = this.changeForm.newAdminId;
          } else {
            param.nickName = this.changeForm.nickName;
            if (this.$i18n.locale === "zh-CN") {
              param.phone = this.changeForm.phone;
            } else {
              param.mail = this.changeForm.mail;
            }
            param.pwd = this.changeForm.password;
          }
          this.saveLoading = true;
          TrainCenterApi.updateTrainCenterAdmin(
            this.changeForm.trainCenterId,
            param
          ).then(
            (res) => {
              this.saveLoading = false;
              this.changeAdminModelVisiable = false;
              this.$Message.success(this.$t("sysP.changSuc"));
              this.fetchDataList();
            },
            (error) => {
              this.saveLoading = false;
              this.$Message.error(error.response.data.msg);
            }
          );
        }
      });
    },
  },
  created() {
    console.log("进入created");
    this.search();
  },
  activated() {
    console.log("进入activated");
    const router_from = this.$store.getters.routerFrom;
    console.log("跳转来源:" + router_from);
    const right_main = document.getElementById("right_main");
    if (!isEmpty(router_from) && router_from == "companyDetail") {
      console.log("activated滚动到：" + this.scrollTop);
      right_main.scrollTop = this.scrollTop;
    } else {
      this.scrollTop = 0;
      console.log("activated无须滚动");
      right_main.scrollTop = this.scrollTop;
      this.currentPage = 1;
      this.fetchDataList();
    }
  },
};
</script>
